<?php

class Admin_LaboratorioController extends Zend_Controller_Action {

    private $_logger;
    private $_debugLog;
    private $_errorMessages;
    private $_defaultMessages;
    private $_warningMessages;
    private $vlabNamespace;

    /**
     * 
     */
    public function init() {
        $this->view->profe = "2";
        $this->_errorMessages = Zend_Registry::get(VirtualLabs_Common::ERROR_MESSAGES);
        $this->_defaultMessages = Zend_Registry::get(VirtualLabs_Common::DEFAULT_MESSAGES);
        $this->_warningMessages = Zend_Registry::get(VirtualLabs_Common::WARNING_MESSAGES);

        $this->view->deleteConfirmMessage = $this->_defaultMessages->delete_confirm_message;
        $this->_logger = Zend_Registry::get(VirtualLabs_Common::ERROR_LOG);
        $this->_debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);

        // sesion para editar el laboratorio en sesion
        $this->vlabNamespace = new Zend_Session_Namespace('vlab');
    }

    /**
     * 
     */
    public function preDispatch() {
        // Autenticacion del usuario
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_helper->layout->disableLayout();
            $this->_forward("index", "index", "");
        } else {
            $identity = $auth->getIdentity();
            if ($identity['tipo_usuario'] != VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                $this->_helper->layout->disableLayout();
                $this->_redirect('/');
            }
        }
        //fin de la autenicacion del usuario
    }

    /**
     * 
     */
    public function indexAction() {
        
    }

    /**
     * 
     */
    public function deployvmAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $params = $this->getRequest()->getParams();

        if ($params["vms"]) {
            $vms = Zend_Json_Decoder::decode($params["vms"]);
            // Utilizamos un solo objeto del API para la creacion de todas las VMS
            $vm = new VirtualLabs_Rest_VirtualLabs_VirtualMachine();

            $laboratorio = new VirtualLabs_Admin_Laboratorio();
            $projectData = $laboratorio->getLaboratorio(array("codigo_proyecto", "nombre"), array("codigo_laboratorio" => array('criteria' => '=', 'value' => $params['labCode'])));
            $labName = str_replace(" ", "-", strtolower($projectData["nombre"]));
            $projectId = $projectData['codigo_proyecto'];
            $number = 0;
            $responseControl = array();
            foreach ($vms as $row) {
//                recuperamos parametros por cada grupo de vms similares
                $cantidad = $row["cantidad"];
                $serviceOffering = $row["serviceOffering"];
                $diskOffering = $row["diskOffering"];
                $template = $row["template"];

//                itera sobre la cantidad y crea vms similares
                $virtualMachine = new VirtualLabs_Admin_Machine();
                for ($i = 0; $i < $cantidad; $i++) {
//                    inserta en la base de datos local los datos de la maquina virtual
                    try {
                        $this->_debugLog->debug("[ Creating ] service-offering " .
                                "'$serviceOffering' disk-offering '$diskOffering' lab-name " .
                                "'$labName-$number' template '$template' projectid '{$projectId}'");
                        $vmName = "$labName-$number-" . date("dmYGis");
                        $response = $vm->createVM($serviceOffering, $diskOffering, $vmName, $template, $projectId);
                    } catch (Exception $e) {
                        $this->_logger->err($e->getMessage());
                        $this->_logger->err($e->getTraceAsString());
                    }
                    $arrayRepresentation = Zend_Json_Decoder::decode($response);

                    if (isset($arrayRepresentation['deployvirtualmachineresponse']['jobid'])) {
//                        almacenamos referencias tanto al trabajo en batch del cloudstack como al registro local de la maquina virtual

                        $virtualMachineData = $virtualMachine->save(VirtualLabs_Admin_Machine::TABLE_NAME, array('codigo_laboratorio' => $params['labCode'],
                            'estado' => VirtualLabs_Admin_Machine::ESTADO_CREACION,
                            'async_job_id' => $arrayRepresentation['deployvirtualmachineresponse']['jobid']), array('key' => 'codigo_maquina_virtual', 'value' => null));
                        $this->_debugLog->debug("[ vm-local database added ] " . print_r($virtualMachineData, true));
                        $responseControl[$number]['vm_code'] = $virtualMachineData['codigo_maquina_virtual']; // base de datos local
                        $responseControl[$number]['jobid'] = $arrayRepresentation['deployvirtualmachineresponse']['jobid'];
                        $responseControl[$number]['status'] = VirtualLabs_Admin_Machine::ESTADO_CREACION;
                        $number++;
                    } else {
                        $virtualMachineData = $virtualMachine->save(VirtualLabs_Admin_Machine::TABLE_NAME, array('codigo_laboratorio' => $params['labCode'],
                            'estado' => VirtualLabs_Admin_Machine::ESTADO_ERROR,
                            'async_job_id' => ''), array('key' => 'codigo_maquina_virtual', 'value' => null));
//                        manejar error al crear la vm en el cloudstack
                        $responseControl[$number++]['error'] = $arrayRepresentation['deployvirtualmachineresponse']['errorcode'] . " - " . $arrayRepresentation['deployvirtualmachineresponse']['errortext'];
                        $responseControl[$number++]['status'] = VirtualLabs_Admin_Machine::ESTADO_ERROR;
                    }
                }
            }
            echo Zend_Json_Encoder::encode($responseControl);
        }
    }

    /**
     * Esto debe invocarse al iniciar
     */
    public function checkresourcesAction() {
        $codigo_curso = $this->getRequest()->getParam("id");
        $form = new Admin_Form_Curso();
        if (isset($codigo_curso)) {
            $curso = new Application_Model_Curso();
            $curso_db = $curso->find($this->getRequest()->getParam("id"));

            $form->populate($curso_db->toArray());
        }
        $this->view->form = $form;
    }

    /**
     * Crea una red virtual en el cloudstack, asociada al proyecto que representa el laboratorio virtual.
     * 
     * @return JSON
     * @throws Exception
     */
    public function createnetworkAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $network = new VirtualLabs_Rest_Network_Network();
        $laboratorio = new VirtualLabs_Admin_Laboratorio();
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        $this->_debugLog->debug("[ createNetwork ] lab {$this->getRequest()->getParam('codigo_laboratorio')} gw {$this->getRequest()->getParam('gateway')} mask {$this->getRequest()->getParam('netmask')}");
        $areaAcademica = new VirtualLabs_Admin_AreaAcademica();
        try {
            if ($codigoLaboratorio) {
                $data = $laboratorio->getLaboratorio(array('codigo_proyecto', 'nombre', 'nombre_mostrar', 'codigo_area_academica'), array('codigo_laboratorio' => array('criteria' => '=', 'value' => $codigoLaboratorio)));
                $ntw = new VirtualLabs_Admin_Network();
                $codigoNetwork = $ntw->getNetworkByLab($codigoLaboratorio);
                $this->_debugLog->debug(" [ createNetwork ] " . print_r($codigoNetwork, true));
                $this->_debugLog->debug(" [ createNetwork ] data " . print_r($data, true));
                $dataArea = $areaAcademica->getAreaAcademica(array('account_id'), array('codigo_area_academica' => array('criteria' => '=', 'value' => $data['codigo_area_academica'])));
                $this->_debugLog->debug(" [ createNetwork ] areaAcademica " . print_r($dataArea, true));
                if (!isset($codigoNetwork['network_id'])) {
//                    si no existe ninguna red asociada
                    $this->_debugLog->debug("[ createNetwork ] project " . $data['codigo_proyecto'] . " account " . $dataArea['account_id'] . " gateway " . $this->getRequest()->getParam('gateway') . " netmask " . $this->getRequest()->getParam('netmask'));
                    $createNetworkResponse = $network->createNetwork($data['nombre'] . "-ntw", $data['nombre_mostrar'] . "-ntw", $data['codigo_proyecto'], $dataArea['account_id'], $this->getRequest()->getParam('gateway'), $this->getRequest()->getParam('netmask'));
                    $this->_debugLog->debug(print_r($createNetworkResponse['createnetworkresponse'], true));
                    if (isset($createNetworkResponse['createnetworkresponse']['network']['id'])) {
                        // verificar $createNetworkResponse['createnetworkresponse']['network']['id']
                        $dao = new VirtualLabs_Admin_Network();
                        $dao->save(VirtualLabs_Admin_Network::TABLE_NAME, array('network_id' => $createNetworkResponse['createnetworkresponse']['network']['id'],
                            'gateway' => $createNetworkResponse['createnetworkresponse']['network']['gateway'],
                            'netmask' => $createNetworkResponse['createnetworkresponse']['network']['netmask'],
                            'cidr' => $createNetworkResponse['createnetworkresponse']['network']['cidr'],
                            'dns1' => $createNetworkResponse['createnetworkresponse']['network']['dns1'],
                            'codigo_laboratorio' => $this->getRequest()->getParam('codigo_laboratorio')));

                        echo Zend_Json_Encoder::encode(array('response' => 'success', array('id' => $createNetworkResponse['createnetworkresponse']['network']['id'])));
                    } elseif (isset($createNetworkResponse['createnetworkresponse']['errorcode'])) {
                        // verificar $createNetworkResponse['createnetworkresponse']['errorcode']
                        // salir por error, no hacer nada.. retornar mensaje error para reintentar
                        echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => $createNetworkResponse['createnetworkresponse']['errortext']));
                    }
                } else {
                    // si existe la red, se elimina para reemplazar la existente (?)
                    // se debe verificar que no haya maquinas virtuales asociadas, sino, se tienen que eliminar las maquinas virtuales
                    $ntw = $network->listNetworks($data['codigo_proyecto'], $dataArea['account_id'], $codigoNetwork[0]['network_id']);
                }
            } else {
                echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => 'Favor indicar el laboratorio'));
                return;
            }
        } catch (Exception $e) {
            echo Zend_Json_Encoder::encode(array('error' => $e->getMessage()));
            throw $e;
        }
    }

    /**
     * Invocado para editar un laboratorio existente o mostrar un formulario de creacion de un laboratorio nuevo.
     * 
     */
    public function editAction() {
        try {
            $codigo_laboratorio = $this->getRequest()->getParam("id");

            if (is_numeric($codigo_laboratorio)) {
                $this->_logger->debug("codigo_laboratorio : $codigo_laboratorio");
                $laboratorio = new VirtualLabs_Admin_Laboratorio();
                $laboratorioData = $laboratorio->getLaboratorios("*", array("codigo_laboratorio" => array("criteria" => "=", "value" => $codigo_laboratorio)));
                $this->populateForm($laboratorioData[0]);
            } else if (is_numeric($this->vlabNamespace->codigoLaboratorio)) {
                $this->_logger->debug("codigo_laboratorio : " . $this->vlabNamespace->codigoLaboratorio);
                $laboratorio = new VirtualLabs_Admin_Laboratorio();
                $laboratorioData = $laboratorio->getLaboratorios("*", array("codigo_laboratorio" => array("criteria" => "=", "value" => $this->vlabNamespace->codigoLaboratorio)));
                $this->populateForm($laboratorioData[0]);
            } else {
                $this->_logger->debug("no hay codigo_laboratorio");
                $this->vlabNamespace->codigoLaboratorio = "";
            }
        } catch (Exception $e) {
            $this->_logger->err($e->getMessage());
            $this->_logger->err($e->getTraceAsString());
        }
    }

    /**
     * Carga las variables en la vista del laboratorio a editar. Solo datos generales.
     * 
     * @param array $laboratorioData datos del laboratorio
     */
    private function populateForm($laboratorioData) {
        $this->vlabNamespace->codigoLaboratorio = $laboratorioData['codigo_laboratorio'];
        $this->view->codigoLaboratorio = $laboratorioData['codigo_laboratorio'];
        $this->view->codigoProyecto = $laboratorioData['codigo_proyecto'];
        $this->view->nombre = $laboratorioData['nombre'];
        $this->view->nombreMostrar = $laboratorioData['nombre_mostrar'];
        $this->view->descripcion = $laboratorioData['descripcion'];
        $this->view->fechaInicio = $laboratorioData['fecha_inicio'];
        $this->view->fechaFin = $laboratorioData['fecha_fin'];
        $perfil = new VirtualLabs_Admin_PerfilEncendido();
        $perfilData = $perfil->getPerfilEncendido('*', array('codigo_perfil_encendido' => array('criteria' => '=', 'value' => $laboratorioData['codigo_perfil_encendido'])));
        $this->_debugLog->debug(print_r($perfilData, true));
        $this->view->horaInicio = $perfilData['hora_inicio_dia'];
        $this->view->horaFin = $perfilData['hora_fin_dia'];
        $this->view->diasGuardados = $perfilData['dias_encendido'];
    }

    /**
     * Lista los laboratorios.
     * 
     */
    public function listAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $this->vlabNamespace->codigoLaboratorio = "";
        $aaData = array();
        try {
            $dao = new VirtualLabs_Admin_Laboratorio();
            $list = $dao->getLaboratorios(array('codigo_laboratorio', 'nombre', 'descripcion', 'codigo_matricula', 'fecha_hora_creacion'), array('estado' => array('criteria' => '=', 'value' => 'A')));
            $this->_debugLog->debug(print_r($list, true));
            $response = array();
            foreach ($list as $row) {
                //    $response [] = array($this->view->deleteUrl($row['codigo_laboratorio'], "laboratorio", '#laboratorio-container'),
                $response [] = array("<input type='image' src='/images/trash-icon-50x50.png' onclick='deletelab({$row['codigo_laboratorio']});' title='Eliminar Laboratorio' />",
//                    "<input type='image' src='/images/arrow_down.png' onclick='inactivatelab({$row['codigo_laboratorio']});' title='Inactivar Laboratorio' />",
                    $this->view->assignAlumnoLabUrl($row['codigo_laboratorio']),
                    $this->view->viewVmsUrl($row['codigo_laboratorio']),
                    $this->view->editUrl($row['codigo_laboratorio'], $row['nombre'], "laboratorio"), $row['descripcion'],
                    $row['codigo_matricula']
//                        , $row['fecha_hora_creacion']
                );
            }
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getTraceAsString());
            $aaData['error'] = $exc->getTraceAsString();
        }
        $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $debugLog->debug(print_r($response, TRUE));
        $aaData['aaData'] = $response;
        echo Zend_Json_Encoder::encode($aaData);
    }

    public function listinactiveAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $aaData = array();
        try {
            $dao = new VirtualLabs_Admin_Laboratorio();
            $list = $dao->getLaboratorios(array('codigo_laboratorio', 'nombre', 'descripcion', 'cantidad_maquinas', 'fecha_hora_creacion'), array('estado' => array('criteria' => '=', 'value' => 'I')));
            $this->_debugLog->debug(print_r($list, true));
            $response = array();
            foreach ($list as $row) {
                $response [] = array("<input type='image' src='/images/delete.png' onclick='deletelab({$row['codigo_laboratorio']});' title='Eliminar Laboratorio' />",
                    "<input type='image' src='/images/arrow_up.png' onclick='activatelab({$row['codigo_laboratorio']});' title='Activar Laboratorio' />",
                    $this->view->assignAlumnoLabUrl($row['codigo_laboratorio']),
                    $this->view->viewVmsUrl($row['codigo_laboratorio']),
                    $this->view->editUrl($row['codigo_laboratorio'], $row['nombre'], "laboratorio"), $row['descripcion'],
                    $row['cantidad_maquinas'], $row['fecha_hora_creacion']);
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
            $aaData['error'] = $exc->getTraceAsString();
        }
        $aaData['aaData'] = $response;
        echo Zend_Json_Encoder::encode($aaData);
    }

    /**
     * Asocia los profesores seleccionados en pantalla al presente laboratorio.
     * 
     */
    public function saveprofesoresAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $laboratorio = new VirtualLabs_Admin_Laboratorio();
        $profesores = $this->getRequest()->getParam('profes');
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        $auth = Zend_Auth::getInstance();

        $identity = $auth->getIdentity();

        try {
            if ($profesores) {
                $laboratorio->saveMembers($profesores, $codigoLaboratorio, $identity['username']);
                echo Zend_Json_Encoder::encode(array('response' => 'success'));
            } else {
                echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => 'Seleccione un profesor'));
            }
        } catch (Exception $e) {
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => $e->getMessage()));
        }
    }

    /**
     * Obtiene informacion sobre la red virtual del cloudstack asociada al proyecto que representa al laboratorio.
     * 
     */
    public function getnetworkAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigoLaboratorio = $this->getRequest()->getParam("codigo_laboratorio");

        // el proyecto al que pertenece el lab en cloudstack
        $laboratorioDao = new VirtualLabs_Admin_Laboratorio();
        $laboratorio = $laboratorioDao->getLaboratorio(array('codigo_proyecto', 'codigo_area_academica'), array('codigo_laboratorio' => array('criteria' => '=', 'value' => $codigoLaboratorio)));
        $this->_debugLog->debug(print_r($laboratorio, true));

        // el account_id con el que creamos el proyecto
        $areaAcademicaDao = new VirtualLabs_Admin_AreaAcademica();
        $areaAcademica = $areaAcademicaDao->getAreaAcademica(array('account_id'), array('codigo_area_academica' => array('criteria' => '=', 'value' => $laboratorio['codigo_area_academica'])));
        $this->_debugLog->debug(print_r($areaAcademica, true));
        // el codigo de red que tiene asociado
        $networkDao = new VirtualLabs_Admin_Network();
        $network = $networkDao->getNetworkByLab($codigoLaboratorio);
        if ($network) {
            $this->_debugLog->debug(print_r($network, true));
            $networkCloud = new VirtualLabs_Rest_Network_Network();
            $networkCloudData = $networkCloud->listNetworks($laboratorio['codigo_proyecto'], $areaAcademica['account_id'], $network['network_id']);

            if (isset($networkCloudData['listnetworksresponse']['network'])) {
                $this->_debugLog->debug(print_r($networkCloudData, true));
                $ip = explode('/', $networkCloudData['listnetworksresponse']['network'][0]['cidr']);
                echo Zend_Json_Encoder::encode(array('ip' => $ip[0], 'gw' => $networkCloudData['listnetworksresponse']['network'][0]['gateway'], 'netmask' => $networkCloudData['listnetworksresponse']['network'][0]['netmask']));
            } else {
                echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => $networkCloudData['listnetworksresponse']['errorcode'] . " - " . $networkCloudData['listnetworksresponse']['errortext']));
            }
        } else {
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => $this->_warningMessages->no_network));
        }
    }

    /**
     * Elimina la asociacion de alumno 'username' a un laboratorio 'codigo_laboratorio'
     * 
     */
    public function desasociarAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        $alumno = $this->getRequest()->getParam('username');
        $laboratorioDao = new VirtualLabs_Admin_Laboratorio();
        $maquinavirtualDao = new VirtualLabs_Academico_Machine();
        $maquinavirtualadminDao = new VirtualLabs_Admin_Machine();
        $vmRest = new VirtualLabs_Rest_VirtualLabs_VirtualMachine();
        $grupoperfilDao = new VirtualLabs_Admin_GrupoPerfil();
        $this->_debugLog->debug("[ desasociar ] : laboratorio->$codigoLaboratorio username->{$alumno}");
        try {
//            eliminamos la maquina de la faz de la tierra
            $codigoVmTmp = $maquinavirtualDao->getVmsInLab($codigoLaboratorio, $alumno);
            $laboratorioDao->desasociarMiembro($alumno, $codigoLaboratorio, VirtualLabs_Admin_Usuario::ROL_ALUMNO);
            $this->_debugLog->debug("[vms in lab] " . print_r($codigoVmTmp, true));
            if ($codigoVmTmp) {
                foreach ($codigoVmTmp as $c) {
                    $codigoVM = array('key' => 'codigo_maquina_virtual', 'value' => $c['codigo_maquina_virtual']);
                    $maquinavirtualadminDao->deleteMiembrosAsociadosVM($codigoVM);
                    $maquinavirtualadminDao->deleteVM($codigoVM);
                    $this->_debugLog->debug("[erase from cloud codigo_vm] " . $c['codigo_vm']);
                    $vmRest->deleteVM($c['codigo_vm']);
                }
            }
            $grupoPerfil = $grupoperfilDao->getGrupoPerfilByCodigoLaboratorio($codigoLaboratorio);
            $grupoperfilDao->save(VirtualLabs_Admin_GrupoPerfil::TABLE_NAME, array('cantidad_creada' => ($grupoPerfil['cantidad_creada'] - 1)), array('key' => 'codigo_grupo_perfil_vm', 'value' => $grupoPerfil['codigo_grupo_perfil_vm']));
            echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_SUCCESS));
        } catch (Exception $e) {
            $this->_logger->err($e->getMessage());
            $this->_logger->err($e->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_ERROR, 'msg' => $e->getMessage()));
        }
    }

    public function asociaalumnoAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        $alumno = Zend_Json_Decoder::decode($this->getRequest()->getParam('alumno'));
        $laboratorioDao = new VirtualLabs_Admin_Laboratorio();
        $this->_debugLog->debug("[ asociar ] : laboratorio->$codigoLaboratorio username->{$alumno['username']}");
        try {
            $laboratorioDao->agregarMiembro(array('username' => $alumno['username'], 'rol' => VirtualLabs_Admin_Usuario::ROL_ALUMNO), $codigoLaboratorio);
            echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_SUCCESS));
        } catch (Exception $e) {
            $this->_logger->err($e->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_ERROR));
        }
    }

    /**
     * Inserta un nuevo alumno a la base de datos y luego asocia dicho alumno al laboratorio codigo_laboratorio
     * recibido como parametro.
     * 
     */
    public function agregarasociarAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $alumno = Zend_Json_Decoder::decode($this->getRequest()->getParam('alumno'));
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        $usuarioDao = new VirtualLabs_Admin_Usuario();
        $laboratorioDao = new VirtualLabs_Admin_Laboratorio();
        try {
            $alumno['tipo_usuario'] = VirtualLabs_Admin_Usuario::ROL_ALUMNO;
            // se agrega el usuario
            $usuarioDao->save(VirtualLabs_Admin_Usuario::TABLE_NAME, $alumno);

//            agregamos el usuario al laboratorio
            $laboratorioDao->agregarMiembro(array('username' => $alumno['username'], 'rol' => VirtualLabs_Admin_Usuario::ROL_ALUMNO), $codigoLaboratorio);
            echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_SUCCESS));
        } catch (Exception $e) {
            $this->_logger->err($e->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => VirtualLabs_Common::RESPONSE_ERROR, VirtualLabs_Common::RESPONSE_MESSAGE => $e->getMessage()));
        }
    }

    public function groupscreatedAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        try {
            $grupoPerfil = new VirtualLabs_Admin_GrupoPerfil();
            $perfilLaboratorio = $grupoPerfil->getGrupoPerfilByCodigoLaboratorio($codigoLaboratorio);
            $response = array();

            foreach ($perfilLaboratorio as $p) {
                $row = array();
//                cantidad de grupos de perfiles solicitados
                $row[] = $p['cantidad'];

                $perfiles = $grupoPerfil->getPerfiles($p['codigo_grupo_perfil_vm']);
                $cantidad_perfiles = 0;
                $htmlPerfiles = "<ul>";
                foreach ($perfiles as $prof) {
                    $htmlPerfiles .= "<li>{$prof['descripcion']}</li>";
                    $cantidad_perfiles++;
                }
                $htmlPerfiles .= "</ul>";

//                cantidad de maquinas virtuales
                $row[] = $cantidad_perfiles * $p['cantidad'];

//                descripciones de los sistemas base
                $row[] = ($htmlPerfiles);
                $response [] = $row;
            }
            $response['aaData'] = $response;
            $this->_logger->debug(print_r($response, true));

            echo Zend_Json_Encoder::encode($response);
        } catch (Exception $e) {
            echo Zend_Json_Encoder::encode(array('response' => 'error'));
        }
    }

    public function creargrupoAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        try {
//        recibimos los parametros
            $perfiles = Zend_Json_Decoder::decode($this->getRequest()->getParam("perfiles"));
            $codigoLaboratorio = $this->getRequest()->getParam("codigo_laboratorio");
            $projectRest = new VirtualLabs_Rest_VirtualLabs_Project();
            if (!$codigoLaboratorio) {
                echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => 'Favor vuelva a crear el laboratorio.'));
                return;
            }
            $cantidad = $this->getRequest()->getParam("cantidad");
            $asignable = $this->getRequest()->getParam("asignable");
            $grupoPerfil = new VirtualLabs_Admin_GrupoPerfil();

//        verificamos la existencia de un grupo asignable a alumnos

            $existe = $grupoPerfil->existeAsignado($codigoLaboratorio);

            if (count($existe) > 1 && $asignable === "true") {
                echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => 'Solo puede crear un grupo de perfiles asignable.'));
                return;
            }

//        creamos el grupo de perfiles
            if ($asignable === "true") {
                $asignable = VirtualLabs_Common::GRUPO_PERFIL_ASIGNABLE;
            } else {
                $asignable = VirtualLabs_Common::GRUPO_PERFIL_NO_ASIGNABLE;
            }
            $data = array('codigo_laboratorio' => $codigoLaboratorio, 'cantidad' => $cantidad, 'asignable' => $asignable);
            $nuevoGrupoPerfil = $grupoPerfil->save(VirtualLabs_Admin_GrupoPerfil::TABLE_NAME, $data, array('key' => 'codigo_grupo_perfil_vm', 'value' => null));
            $ocurriorError = false;
            $this->_debugLog->debug(print_r($nuevoGrupoPerfil, true));
            foreach ($perfiles as $perfil) {
//            guardamos los perfiles
                try {
                    $dataPerfil = array('descripcion' => $perfil['descripcion_template'], 'service_offering' => $perfil['serviceOffering'], 'disk_offering' => $perfil['diskOffering'], 'template' => $perfil['template'], 'codigo_grupo_perfil_vm' => $nuevoGrupoPerfil['codigo_grupo_perfil_vm']);
                    $this->_debugLog->debug(print_r($dataPerfil, true));
                    $grupoPerfil->savePerfil($dataPerfil);
                } catch (Exception $perfilEx) {
                    $this->_logger->err($perfilEx->getTraceAsString());
                    $ocurriorError = true;
                }
            }
            if ($ocurriorError) {
                echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => 'Ha ocurrido un error durante el proceso. Favor contactar con el administrador.'));
                return;
            }

//        actualizar el limite del proyecto
            $cantidadTotal = $grupoPerfil->getCantidadVmByCodigoLaboratorio($codigoLaboratorio);
            $labDao = new VirtualLabs_Admin_Laboratorio();
            $codigoProyecto = $labDao->getCodigoProyecto($codigoLaboratorio);
            $projectRest->updateVmLimit($codigoProyecto, $cantidadTotal);
            $projectRest->updateVolumeLimit($codigoProyecto, $cantidadTotal * 2);
            echo Zend_Json_Encoder::encode(array('response' => 'success'));
        } catch (Exception $e) {
            $this->_logger->err($e->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => 'error'));
        }
    }

    private function getConsumoPerfiles($perfiles, $cantidad, $offeringsCloud) {
//        calculo el consumo de los perfiles y cantidad solicitados 
        foreach ($perfiles as $perfil) {
//            guardamos los perfiles
            try {
                $data = $offeringsCloud->listServiceOfferingById($perfil['service_offering']);
                $cpuNumber = $data['listserviceofferingsresponse']['serviceoffering'][0]['cpunumber'];
                $cpuSpeed = $data['listserviceofferingsresponse']['serviceoffering'][0]['cpuspeed'];
                $cpu = $cpuNumber * $cpuSpeed;
                $memory = $data['listserviceofferingsresponse']['serviceoffering'][0]['memory'];
                $tmpConsumoPerfiles ['cpu'] += $cpu * $cantidad;
                $tmpConsumoPerfiles ['memory'] += $memory * $cantidad;
                $this->_debugLog->debug(print_r($data, true));
            } catch (Exception $perfilEx) {
                $this->_logger->err($perfilEx->getTraceAsString());
                throw $perfilEx;
            }
        }
        return $tmpConsumoPerfiles;
    }

    public function controlavailabletocreateAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        //        recibimos los parametros
        $perfiles = Zend_Json_Decoder::decode($this->getRequest()->getParam("perfiles"));
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        if (!$codigoLaboratorio) {
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => 'Favor vuelva a crear el laboratorio.'));
            return;
        }
        $cantidad = $this->getRequest()->getParam("cantidad");
        $offeringsCloud = new VirtualLabs_Rest_VirtualLabs_Offerings();
        $perfilPlataforma = new VirtualLabs_Admin_Capacity();
        $perfilEncendido = new VirtualLabs_Admin_PerfilEncendido();
        $diasSemana = array('Do' => 0, 'Lu' => 1, 'Ma' => 2, 'Mi' => 3, 'Ju' => 4, 'Vi' => 5, 'Sa' => 6);
        $resources = new VirtualLabs_Reserved();

        try {
            $tmpConsumoPerfiles = $this->getConsumoPerfiles($perfiles, $cantidad, $offeringsCloud);
            $consumoPerfiles = array('cpu' => $tmpConsumoPerfiles['cpu'] * 100 / $resources->getTotalCpu(), 'memory' => $tmpConsumoPerfiles['memory'] * 100 / $resources->getTotalMemory());

//      los grupos no desplegados
            $tmpConsumoNoDesplegado = $this->consumoNoDesplegado($codigoLaboratorio);
            $consumoNoDesplegado = array('cpu' => ($tmpConsumoNoDesplegado['cpu'] * 100 / $resources->getTotalCpu()), 'memory' => ($tmpConsumoNoDesplegado['memory'] * 100 / $resources->getTotalMemory()));
            $perfilEncendidoLaboratorio = $perfilEncendido->getPerfilEncendidoByLab($codigoLaboratorio);
            $this->_debugLog->debug("consumoNoDesplegado : " . print_r($consumoNoDesplegado, true));

//        recursos utilizados en la plataforma en los dias y horarios que el 
//        perfil de encendido del laboratorio coinciden
            $inicio = explode(":", $perfilEncendidoLaboratorio['hora_inicio_dia']);
            $fin = explode(":", $perfilEncendidoLaboratorio['hora_fin_dia']);


            $resourcesUsed = $resources->getReserverdByTimeRange(explode(",", $perfilEncendidoLaboratorio['dias_encendido']), array('inicio' => $inicio[0], 'fin' => $fin[0]));

//            si no hay recursos usados
            if (count($resourcesUsed) == 0) {
                $resourcesUsed = array('cpu' => 0, 'memory' => 0);
            } else {
                $this->_debugLog->debug("resourcesUsed : " . print_r($resourcesUsed, true));
            }

//        limites reservados en la plataforma por horario
            $plataforma = $perfilPlataforma->getAllConfigCapacity();
            $permite = 1;
            $this->_debugLog->debug(print_r($plataforma, true));
//        la nueva carga de capacidad de computo
            if (!isset($perfilEncendidoLaboratorio['dias_encendido'])) {
                $permite = 0;
            } else {
                $this->_debugLog->debug("perfilEncendidoLaboratorio : " . print_r(explode(",", $perfilEncendidoLaboratorio['dias_encendido']), true));
                foreach (explode(",", $perfilEncendidoLaboratorio['dias_encendido']) as $v) {
                    foreach ($plataforma as $p) {
                        if ($p['dia'] == $diasSemana[$v]) {
//                    inicia dentro de este rango global
                            $this->_debugLog->debug("Horario plataforma {$p['hora_inicio']} - {$p['hora_fin']}");
                            $this->_debugLog->debug("Horario perfilencendido {$perfilEncendidoLaboratorio['hora_inicio_dia']} - {$perfilEncendidoLaboratorio['hora_fin_dia']}");
                            $this->_debugLog->debug("INICIO : " . strtotime(date('Y-m-d') . " " . $p['hora_inicio']) . " <= " . strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_inicio_dia']) . " && " . strtotime(date('Y-m-d') . " " . $p['hora_fin']) . " >= " . strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_inicio_dia']));
                            if ((strtotime(date('Y-m-d') . " " . $p['hora_inicio']) <= strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_inicio_dia'])) && (strtotime(date('Y-m-d') . " " . $p['hora_fin']) >= strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_inicio_dia']) )) {

//                                compara cpu
                                if (isset($resourcesUsed[$v])) {
                                    $this->_debugLog->debug("Comparacion CPU : {$p['cantidad_cpu']} < ({$consumoNoDesplegado['cpu']} + {$resourcesUsed[$v]['cpu']} + {$consumoPerfiles['cpu']})");
                                    if ($p['cantidad_cpu'] < ($consumoNoDesplegado['cpu'] + $resourcesUsed[$v]['cpu'] + $consumoPerfiles['cpu'])) {
                                        $permite = 0;
                                        $this->_debugLog->debug("NO hay suficiente CPU [plataforma] {$p['cantidad_cpu']} < " . ($consumoNoDesplegado['cpu'] + $resourcesUsed[$v]['cpu'] + $consumoPerfiles['cpu']) . " [requerido]");
                                    } else {
                                        $this->_debugLog->debug("Hay suficiente CPU [plataforma] {$p['cantidad_cpu']} < " . ($consumoNoDesplegado['cpu'] + $resourcesUsed[$v]['cpu'] + $consumoPerfiles['cpu']) . " [requerido]");
                                    }
                                } else {
                                    $this->_debugLog->debug("Comparacion CPU > {$p['cantidad_cpu']} < ({$consumoNoDesplegado['cpu']} + {$resourcesUsed['cpu']} + {$consumoPerfiles['cpu']})");
                                    if ($p['cantidad_cpu'] < ($consumoNoDesplegado['cpu'] + $resourcesUsed['cpu'] + $consumoPerfiles['cpu'])) {
                                        $permite = 0;
                                        $this->_debugLog->debug("NO hay suficiente CPU [plataforma] {$p['cantidad_cpu']} < " . ($consumoNoDesplegado['cpu'] + $resourcesUsed['cpu'] + $consumoPerfiles['cpu']) . " [requerido]");
                                    } else {
                                        $this->_debugLog->debug("Hay suficiente CPU [plataforma] {$p['cantidad_cpu']} < " . ($consumoNoDesplegado['cpu'] + $resourcesUsed['cpu'] + $consumoPerfiles['cpu']) . " [requerido]");
                                    }
                                }

//                                compara memoria
                                if (isset($resourcesUsed[$v])) {
                                    $this->_debugLog->debug("Comparacion RAM : {$p['cantidad_ram']} < ({$consumoNoDesplegado['memory']} + {$resourcesUsed[$v]['memory']} + {$consumoPerfiles['memory']})");
                                    if ($p['cantidad_ram'] < ($consumoNoDesplegado['memory'] + $resourcesUsed[$v]['memory'] + $consumoPerfiles['memory'])) {
                                        $permite = 0;
                                        $this->_debugLog->debug("NO hay suficiente MEMORIA [plataforma] {$p['cantidad_ram']} < " . ($consumoNoDesplegado['memory'] + $resourcesUsed[$v]['memory'] + $consumoPerfiles['memory']) . " [requerido]");
                                    } else {
                                        $this->_debugLog->debug("Hay suficiente MEMORIA [plataforma] {$p['cantidad_ram']} < " . ($consumoNoDesplegado['memory'] + $resourcesUsed[$v]['memory'] + $consumoPerfiles['memory']) . " [requerido]");
                                    }
                                } else {
                                    $this->_debugLog->debug("Comparacion RAM : {$p['cantidad_ram']} < ({$consumoNoDesplegado['memory']} + {$resourcesUsed['memory']} + {$consumoPerfiles['memory']})");
                                    if ($p['cantidad_ram'] < ($consumoNoDesplegado['memory'] + $resourcesUsed['memory'] + $consumoPerfiles['memory'])) {
                                        $permite = 0;
                                        $this->_debugLog->debug("NO hay suficiente MEMORIA [plataforma] {$p['cantidad_ram']} < " . ($consumoNoDesplegado['memory'] + $resourcesUsed['memory'] + $consumoPerfiles['memory']) . " [requerido]");
                                    } else {
                                        $this->_debugLog->debug("Hay suficiente MEMORIA [plataforma] {$p['cantidad_ram']} < " . ($consumoNoDesplegado['memory'] + $resourcesUsed['memory'] + $consumoPerfiles['memory']) . " [requerido]");
                                    }
                                }
                            } else {
                                $this->_debugLog->debug("el horario inicio del perfilencendido laboratorio no esta dentro del rango de la plataforma");
                            }

//                    termina dentro de este rango global
                            $this->_debugLog->debug("FIN : " . strtotime(date('Y-m-d') . " " . $p['hora_inicio']) . " <= " . strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_fin_dia']) . " && " . strtotime(date('Y-m-d') . " " . $p['hora_fin']) . " >= " . strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_fin_dia']));
                            if ((strtotime(date('Y-m-d') . " " . $p['hora_inicio']) <= strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_fin_dia'])) && (strtotime(date('Y-m-d') . " " . $p['hora_fin']) > strtotime(date('Y-m-d') . " " . $perfilEncendidoLaboratorio['hora_fin_dia']))) {
                                if (isset($resourcesUsed[$v])) {
                                    if ($p['cantidad_cpu'] < ($consumoNoDesplegado['cpu'] + $resourcesUsed[$v]['cpu'] + $consumoPerfiles['cpu'])) {
                                        $permite = 0;
                                    }
                                } else {
                                    if ($p['cantidad_cpu'] < ($consumoNoDesplegado['cpu'] + $resourcesUsed['cpu'] + $consumoPerfiles['cpu'])) {
                                        $permite = 0;
                                    }
                                }
                                if (isset($resourcesUsed[$v])) {
                                    if ($p['cantidad_ram'] < ($consumoNoDesplegado['memory'] + $resourcesUsed[$v]['memory'] + $consumoPerfiles['memory'])) {
                                        $permite = 0;
                                    }
                                } else {
                                    if ($p['cantidad_ram'] < ($consumoNoDesplegado['memory'] + $resourcesUsed['memory'] + $consumoPerfiles['memory'])) {
                                        $permite = 0;
                                    }
                                }
                            } else {
                                $this->_debugLog->debug("el horario fin del perfilencendido laboratorio no esta dentro del rango de la plataforma");
                            }
                        }
                    }
                }
            }
//            echo Zend_Json_Encoder::encode(array('response' => $permite));
            echo Zend_Json_Encoder::encode(array('response' => 1));
        } catch (Exception $e) {
//            echo Zend_Json_Encoder::encode(array('response' => 0));
            echo Zend_Json_Encoder::encode(array('response' => 1));
            $this->_logger->err($e->getTraceAsString());
        }
    }

    private function getConsumoLab($codigoLaboratorio) {
        $resources = new VirtualLabs_Reserved();

        $perfil = new VirtualLabs_Admin_PerfilEncendido();
        $tmp = $resources->getPlatformResources();
        foreach ($tmp as $k => $v) {
            $tmp[$k] = str_replace(".", "", $v);
        }

        $consumoTotal = $resources->normalize($tmp);
        $this->_debugLog->debug(print_r($consumoTotal, true));
        //        desplegado en la infraestructura
        $perfilData = $perfil->getPerfilEncendidoByLab($codigoLaboratorio);
        $diasDecode = array('Lu' => 'Lunes', 'Ma' => 'Martes', 'Mi' => 'Mi&eacute;rcoles', 'Ju' => 'Jueves', 'Vi' => 'Viernes', 'Sa' => 'S&aacute;bado', 'Do' => 'Domingo');
        if (count($perfilData) > 0) {
            $usedResources = $resources->getReserverdByTimeRange(explode(",", $perfilData['dias_encendido']), array('inicio' => substr($perfilData['hora_inicio_dia'], 0, 2),
                'fin' => substr($perfilData['hora_fin_dia'], 0, 2)));
            foreach ($usedResources as $key => $value) {
                $response[$key] = array('dia' => $diasDecode[$key],
                    'hora_inicio' => $perfilData['hora_inicio_dia'],
                    'hora_fin' => $perfilData['hora_fin_dia'],
                    'memory' => $value['memory'],
                    'cpu' => $value['cpu']);
            }
//          no desplegado en la plataforma
            $consumoPerfiles = $this->consumoNoDesplegado($resources, $codigoLaboratorio, $consumoTotal);
            if (count($consumoPerfiles) > 0) {
//                se agrega el consumo
                $this->_debugLog->debug(print_r($consumoPerfiles, true));
                $consumo = $resources->normalize($consumoPerfiles);
                foreach ($response as $key => $value) {
                    $this->_debugLog->debug("consumo $key/$value");
                    $response[$key]['cpu'] += round($consumo['cpu'] * 100 / $consumoTotal ['cpu'], 0);
                    $response[$key]['memory'] += round($consumo['memory'] * 100 / $consumoTotal ['memory'], 0);
                }
            }
            $response['response'] = "success";
            return $response;
        } else {
            return;
        }
    }

    /**
     * Verifica la capacidad de computo necesaria para desplegar $cantidad - $cantidadCreada en la configuracion de perfil del laboratorio.
     * 
     * @param type $resources
     * @param type $codigoLaboratorio
     * @param type $consumoTotal
     * @return type
     */
    private function consumoNoDesplegado($codigoLaboratorio) {
        //            no desplegado en la infraestructura
        $grupoPerfilVm = new VirtualLabs_Admin_GrupoPerfil();
        $grupoPerfiles = $grupoPerfilVm->getGrupoPerfilByCodigoLaboratorio($codigoLaboratorio);
        $consumoPerfiles = array();
        foreach ($grupoPerfiles as $grupo) {
            $c = $grupo['cantidad'] - $grupo['cantidad_creada'];
            if ($c > 0) {
                $perfiles = $grupoPerfilVm->getPerfiles($grupo['codigo_grupo_perfil_vm']);
                $offeringsCloud = new VirtualLabs_Rest_VirtualLabs_Offerings();

                foreach ($perfiles as $perfil) {

                    $data = $offeringsCloud->listServiceOfferingById($perfil['service_offering']);
                    $cpuNumber = $data['listserviceofferingsresponse']['serviceoffering'][0]['cpunumber'];
                    $cpuSpeed = $data['listserviceofferingsresponse']['serviceoffering'][0]['cpuspeed'];
                    $cpu = $cpuNumber * $cpuSpeed;
                    $memory = $data['listserviceofferingsresponse']['serviceoffering'][0]['memory'];
//                    number_format($c['capacitytotal'], 0, ",", ".");
                    $consumoPerfiles['cpu'] += ($cpu * $c);
                    $consumoPerfiles['memory'] += ($memory * $c);
                }
            }
        }

        if (count($consumoPerfiles) > 0) {
            $consumoPerfiles['cpu'] = $consumoPerfiles['cpu'];
            $consumoPerfiles['memory'] = $consumoPerfiles['memory'];
            return $consumoPerfiles;
        }
        return;
    }

    public function getconsumolabAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        $resources = new VirtualLabs_Reserved();
        $perfil = new VirtualLabs_Admin_PerfilEncendido();
        $tmp = $resources->getPlatformResources();
        foreach ($tmp as $k => $v) {
            $tmp[$k] = str_replace(".", "", $v);
        }

        $consumoTotal = $resources->normalize($tmp);
        $this->_debugLog->debug("Consumo total : " . print_r($consumoTotal, true));

//        desplegado en la infraestructura
        $perfilData = $perfil->getPerfilEncendidoByLab($codigoLaboratorio);
        $diasDecode = array('Lu' => 'Lunes', 'Ma' => 'Martes', 'Mi' => 'Mi&eacute;rcoles', 'Ju' => 'Jueves', 'Vi' => 'Viernes', 'Sa' => 'S&aacute;bado', 'Do' => 'Domingo');
        if (count($perfilData) > 0) {
//            no mostramos lo qeu esta desplegado en la plataforma

            $usedResources = $resources->getReserverdByTimeRange(explode(",", $perfilData['dias_encendido']), array('inicio' => substr($perfilData['hora_inicio_dia'], 0, 2),
                'fin' => substr($perfilData['hora_fin_dia'], 0, 2)));
            foreach ($usedResources as $key => $value) {
                $response[$key] = array('dia' => $diasDecode[$key],
                    'hora_inicio' => $perfilData['hora_inicio_dia'],
                    'hora_fin' => $perfilData['hora_fin_dia'],
//                    'memory' => $value['memory'],
                    'memory' => 0,
//                    'cpu' => $value['cpu']
                    'cpu' => 0);
            }

//            no desplegado en la infraestructura
            $grupoPerfilVm = new VirtualLabs_Admin_GrupoPerfil();
            $grupoPerfiles = $grupoPerfilVm->getGrupoPerfilByCodigoLaboratorio($codigoLaboratorio);
            $consumoPerfiles = array();
            foreach ($grupoPerfiles as $grupo) {
                $c = $grupo['cantidad'] - $grupo['cantidad_creada'];
                if ($c > 0) {
                    $perfiles = $grupoPerfilVm->getPerfiles($grupo['codigo_grupo_perfil_vm']);
                    $offeringsCloud = new VirtualLabs_Rest_VirtualLabs_Offerings();

                    foreach ($perfiles as $perfil) {

                        $data = $offeringsCloud->listServiceOfferingById($perfil['service_offering']);
                        $cpuNumber = $data['listserviceofferingsresponse']['serviceoffering'][0]['cpunumber'];
                        $cpuSpeed = $data['listserviceofferingsresponse']['serviceoffering'][0]['cpuspeed'];
                        $cpu = $cpuNumber * $cpuSpeed;
                        $memory = $data['listserviceofferingsresponse']['serviceoffering'][0]['memory'];
                        $consumoPerfiles['cpu'] += $cpu * $c;
                        $consumoPerfiles['memory'] += $memory * $c;
                        $this->_debugLog->debug(print_r($data, true));
                    }
                }
            }
            if (count($consumoPerfiles) > 0) {
                $this->_debugLog->debug(print_r($consumoPerfiles, true));
                $consumo = $resources->normalize($consumoPerfiles);
                foreach ($response as $key => $value) {
                    $response[$key]['cpu'] += round($consumo['cpu'] * 100 / $consumoTotal ['cpu'], 0);
                    $response[$key]['memory'] += round($consumo['memory'] * 100 / $consumoTotal ['memory'], 0);
                }
            }
            $response['response'] = "success";
            echo Zend_Json_Encoder::encode($response);
        } else {
            echo Zend_Json_Encoder::encode(array('response' => 'error'));
        }
    }
    /*public function testlistprojectAction(){
        $id = $this->getRequest()->getParam("id");
        $project = new VirtualLabs_Rest_VirtualLabs_Project();
        $project->listVRouter($id);
    }*/

    public function testlistprojectAction(){
        $id = $this->getRequest()->getParam("id");
        $grupoPerfil = new VirtualLabs_Admin_GrupoPerfil();
        $cantidadTotal = $grupoPerfil->getCantidadVmByCodigoLaboratorio($id);
    }

    public function saveAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $data = $this->getRequest()->getParam("data");
        $codigoLaboratorio = $this->getRequest()->getParam("codigo_laboratorio");
        $auth = Zend_Auth::getInstance();
        $userInfo = $auth->getIdentity();
        $laboratorio = new VirtualLabs_Admin_Laboratorio();
        $areaAcademica = new VirtualLabs_Admin_AreaAcademica();
        $project = new VirtualLabs_Rest_VirtualLabs_Project();
        $this->_debugLog->debug(print_r($data, true));
//                perfil_encendido
        $perfilEncendido = new VirtualLabs_Admin_PerfilEncendido();
        $this->_debugLog->debug(print_r($data['dias_semana'], true));
        $diasSemana = implode(',', array_filter(array_unique($data['dias_semana'])));

        $codigoMatricula = uniqid();

        $laboratorioData = array('codigo_area_academica' => $data['codigo_area_academica'],
            'nombre' => $data['nombre_laboratorio'], 'nombre_mostrar' => $data['nombre_mostrar_laboratorio'],
            'descripcion' => $data['descripcion'], 'fecha_inicio' => $data['fecha_inicio'],
            'fecha_fin' => $data['fecha_fin'], 'username_creador' => $userInfo['username']);


        $this->_debugLog->debug(print_r($laboratorioData, true));
//        utilizado para crear el proyecto
        $accountId = $areaAcademica->getAreasAcademicas(array('account_id'), array('codigo_area_academica' => array('criteria' => '=',
                'value' => $data['codigo_area_academica'])));
        try {
            // si es una creacion, tambien se crea el project en el cloudstack y el perfil de encendido
            if (!$codigoLaboratorio) {
                $this->_debugLog->debug(" [ createProject ] dt {$data['nombre_mostrar_laboratorio']} na {$data['nombre_laboratorio']} ac {$accountId['account_id']}");
                $responseCreate = $project->createProject($data['nombre_mostrar_laboratorio'], $data['nombre_laboratorio'], $accountId['account_id']);
                $laboratorioData['codigo_proyecto'] = $responseCreate['createprojectresponse']['id'];
                $this->_debugLog->debug("[ createProject ] : " . print_r($responseCreate, true));
                if (isset($responseCreate['createprojectresponse']['errorcode'])) {
                    $this->_logger->err("[ errorCodeCreateProject ] " . $responseCreate['createprojectresponse']['errorcode']);
                    $this->_logger->err("[ errorTextCreateProject ] " . $responseCreate['createprojectresponse']['errortext']);
                    echo Zend_Json_Encoder::encode(array('response' => 'error', 'msg' => $responseCreate['createprojectresponse']['errortext']));
                    return;
                }

                $perfilEncendidoData = $perfilEncendido->save(array('hora_inicio_dia' => $data['hora_inicio'],
                    'hora_fin_dia' => $data['hora_fin'],
                    'dias_encendido' => $diasSemana));
                $laboratorioData['codigo_perfil_encendido'] = $perfilEncendidoData['codigo_perfil_encendido'];
            } else {
                $lab = $laboratorio->getLaboratorio('codigo_perfil_encendido', array('codigo_laboratorio' => array('criteria' => '=', 'value' => $codigoLaboratorio)));
                $this->_debugLog->debug("[ codigo_perfil_encendido_update ] : " . $lab['codigo_perfil_encendido']);
                $perfilEncendidoData = $perfilEncendido->save(array('hora_inicio_dia' => $data['hora_inicio'],
                    'hora_fin_dia' => $data['hora_fin'],
                    'dias_encendido' => $diasSemana), $lab['codigo_perfil_encendido']);
                $laboratorioData['codigo_perfil_encendido'] = $perfilEncendidoData['codigo_perfil_encendido'];
            }
        } catch (Exception $e) {
            $this->_logger->err($e->getTraceAsString());
            return;
        }

        if (!$codigoLaboratorio) {
            $codigoLaboratorio = null;
            $laboratorioData['codigo_matricula'] = $codigoMatricula;
        }


        try {
            if (($savedData = $laboratorio->save($laboratorioData, $codigoLaboratorio))) {
                if (isset($savedData['codigo_laboratorio'])) {
                    $this->vlabNamespace->codigoLaboratorio = $savedData['codigo_laboratorio'];
                    $this->_debugLog->debug("entrada en el registro : " . $this->vlabNamespace->codigoLaboratorio);
                    echo Zend_Json_Encoder::encode(array('response' => 'success', 'id' => $savedData['codigo_laboratorio']));
                } else {
                    echo Zend_Json_Encoder::encode(array('error' =>
                        $this->_errorMessages->insert_error));
                }
            } else {
                echo Zend_Json_Encoder::encode(array('error' =>
                    $this->_errorMessages->insert_error));
            }
        } catch (Exception $ex) {
            $this->_logger->err($ex->getTraceAsString());
            return;
        }
    }

    private function getAreaAcademica($codigo_area_academica) {
        $area_model = new Application_Model_AreaAcademica();
        $area_db = $area_model->find($codigo_area_academica);
        return $area_db;
    }

    /**
     * Lista los alumnos asignados al codigo de laboratorio recibido como parametro.
     */
    public function listassignedalumnosAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigoLaboratorio = $this->getRequest()->getParam("codigo_laboratorio");
        $laboratorioDao = new VirtualLabs_Admin_Laboratorio();
        $listaAsignados = $laboratorioDao->getAlumnosInLaboratorio($codigoLaboratorio);
        $retorno = array();
        foreach ($listaAsignados as $value) {
            $retorno [] = array("<a href='#' onclick='desasociar(\"" . $value['username'] . "\")'><i class='icon-trash'></i></a>", $value['username'], $value['nombre'], $value['apellido'], $value['email']);
        }
        echo Zend_Json_Encoder::encode($retorno);
    }

    /**
     * Accion para la vista de alumnos asignados al laboratorio.
     */
    public function labassignAction() {
        $this->view->codigo_laboratorio = $this->getRequest()->getParam("codigo_laboratorio");
    }

    /**
     * Accion de eliminar el laboratorio. 
     */
    public function inactivateAction() {
        $this->_deleteAction = true;
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigo_laboratorio = $this->getRequest()->getParam("id");
        $response = array();
        try {
            if (isset($codigo_laboratorio)) {
                $labDao = new VirtualLabs_Admin_Laboratorio();
                $codigoProyecto = $labDao->getLaboratorio(array('codigo_proyecto'), array('codigo_laboratorio' => array('criteria' => '=', 'value' => $codigo_laboratorio)));
                $this->_debugLog->debug("estoy aca");
                $project = new VirtualLabs_Rest_VirtualLabs_Project();
                //$responseDeleteProject = 
                $project->suspendProject($codigoProyecto['codigo_proyecto']);
                //$this->_debugLog->debug(print_r($responseDeleteProject, true));
                $labDao->save(array('estado' => 'I'), $codigo_laboratorio);
            }
            $response['response'] = 'success';
        } catch (Exception $exc) {
            $response['response'] = 'error';
            $response['message'] = $exc->getMessage();
        }
        echo Zend_Json_Encoder::encode($response);
    }

    public function deleteAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigo_laboratorio = $this->getRequest()->getParam("id");
        $response = array();
        try {
            //primera accion a realizar es eliminar las vms asociadas al laboratorio del cloudstack y la base de datos
            $vmDao = new VirtualLabs_Admin_Machine();
            $virtualMachines = $vmDao->getVirtualMachinesByLab($codigo_laboratorio);
            $this->_debugLog->debug("VM = " . print_r($virtualMachines, TRUE));
            $vmRest = new VirtualLabs_Rest_VirtualLabs_VirtualMachine();
            foreach ($virtualMachines as $vm) {
                $vmRest->deleteVM($vm["codigo_vm"]);
                //Eliminar las maquinas virtuales de la base de datos
                $codigoVM = array('key' => 'codigo_maquina_virtual', 'value' => $vm['codigo_maquina_virtual']);
                $vmDao->deleteMiembrosAsociadosVM($codigoVM);
                $vmDao->deleteVM($codigoVM);
            }
            //segunda accion es eliminar el proyecto y posteriormente el laboratorio
            $labDao = new VirtualLabs_Admin_Laboratorio();
            $codigoProyecto = $labDao->getLaboratorio(array('codigo_proyecto'), array('codigo_laboratorio' => array('criteria' => '=', 'value' => $codigo_laboratorio)));
            $project = new VirtualLabs_Rest_VirtualLabs_Project();
            //$responseDeleteProject = $project->deleteProject($codigoProyecto);
            $responseProject = $project->deleteProject($codigoProyecto['codigo_proyecto']);
            $this->_debugLog->debug("Response Project = " . print_r($responseProject, TRUE));
            $codigoLab = array('key' => 'codigo_laboratorio', 'value' => $codigo_laboratorio);
            $labDao->deleteMiembrosLab($codigoLab);
            $labDao->deleteRedLab($codigoLab);
            $labDao->deleteGrupoVm($codigoLab);
            $labDao->deleteLab($codigoLab);

            //y por ultimo eliminar el laboratorio
            $response['response'] = 'success';
        } catch (Exception $exc) {
            $response['response'] = 'error';
            $response['message'] = $exc->getMessage();
        }
        echo Zend_Json_Encoder::encode($response);
    }

}

